package com.spring.respone;

import com.spring.execption.ExceptionEnum;

import java.util.List;


public class ApiRestResponse<T> {
    private Integer status;
    private String msg;
    private T data;

    private static final int OK_CODE = 10000;
    private static final int FALSE_CODE = 0;
    private static final int SUCCESS_CODE = 1;
    private static final String OK_MSG = "SUCCESS";
    private static final String FALSE_MSG = "FALSE";


    public ApiRestResponse(T data){
        this.data = data ;
        status = OK_CODE ;
        msg = OK_MSG ;
    }

    public ApiRestResponse(Integer status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ApiRestResponse(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public ApiRestResponse() {
        this(FALSE_CODE, FALSE_MSG);
    }

    //成功的时候调用的方法
    public static <T> ApiRestResponse<T> success() {
        return new ApiRestResponse<>(SUCCESS_CODE,OK_MSG);
    }

    public static <T> ApiRestResponse<T> error(){
        return  new ApiRestResponse<>(FALSE_CODE,FALSE_MSG) ;
    }

    //返回具有data的方法
    public static <T> ApiRestResponse<T> success(T result) {
        ApiRestResponse<T> response = new ApiRestResponse<>();
        response.setData(result);
        response.setMsg("success");
        return response;
    }

    //失败时的方法
    public static <T> ApiRestResponse<T> error(Integer code, String msg) {
        return new ApiRestResponse<>(code, msg);
    }

    //失败时的方法  返回的是错误的类型
    public static <T> ApiRestResponse<T> error(ExceptionEnum ex) {
        return new ApiRestResponse<T>(ex.getCode(),ex.getMsg());
    }

    @Override
    public String toString() {
        String strData="NULL" ;
        if(data instanceof List){
            strData = "{" ;
            for(Object o : (List)data){
                strData += o.toString() + ",";
            }
            strData = strData.substring(0,strData.length()) ;
            strData += "}" ;
        }else if(data!=null){
            strData = data.toString() ;
        }
        return "ApiRestResponse{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", data=" + strData +
                '}';
    }

    public Integer getStatus() {
        return status;
    }

    public ApiRestResponse<T> setStatus(Integer status) {
        this.status = status;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public ApiRestResponse<T> setMsg(String msg) {
        this.msg = msg;
        return this ;
    }

    public T getData() {
        return data;
    }

    public ApiRestResponse setData(T data) {
        this.data = data;
        return this ;
    }

    public static int getOkCode() {
        return OK_CODE;
    }

    public static String getOkMsg() {
        return OK_MSG;
    }
}
